package com.example.foo.user.service;

import java.time.LocalDateTime;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.core.PageResult;
import com.example.core.Pageable;
import com.example.foo.user.model.User;
import com.example.foo.user.query.UserQuery;
import com.example.foo.user.dao.UserDao;

@org.springframework.stereotype.Service
public class UserService {

	private final UserDao userDao;

	public UserService(UserDao userDao) {
		this.userDao = userDao;
	}

	// ========== User ==========

	public PageResult<User> findUsers(UserQuery userQuery, Pageable pageable) {
		return userDao.findUsers(userQuery, pageable);
	}

	public List<User> findUsersByIds(List<Long> ids) {
		return userDao.selectBatchIds(ids);
	}

	public User findUserById(Long id) {
		return userDao.selectById(id);
	}

	public User findUserByCellphone(String cellphone) {
		return userDao.selectOne(new QueryWrapper<User>()
				.eq("cellphone", cellphone)
				);
	}

	public User findUserByWxUnionid(String wxUnionid) {
		return userDao.selectOne(new QueryWrapper<User>()
				.eq("wx_unionid", wxUnionid)
				);
	}

	public User createUser(String cellphone, String name, String avatar, String wxUnionid, String wxJson, Long hjyUserId) {
		User user = new User();
		user.setCellphone(cellphone);
		user.setName(name);
		user.setAvatar(avatar);
		user.setWxUnionid(wxUnionid);
		user.setWxJson(wxJson);
		user.setHjyUserId(hjyUserId);

		user.setCreatedAt(LocalDateTime.now());
		userDao.insert(user);

		return user;
	}

	public void updateUser(Long id, String name, String avatar, String wxJson) {
		User user = new User();
		user.setId(id);

		user.setName(name);
		user.setAvatar(avatar);
		user.setWxJson(wxJson);

		user.setUpdatedAt(LocalDateTime.now());
		userDao.updateById(user);
	}

	public void updateUserCellphone(Long id, String cellphone) {
		User user = new User();
		user.setId(id);

		user.setCellphone(cellphone);

		user.setUpdatedAt(LocalDateTime.now());
		userDao.updateById(user);
	}

}
